<template>
  <PageWrapper>
    <Tabs v-model:activeKey="activeKey">
      <TabPane tab="基本信息" key="1">
        <BaseInfo :tableInfo="tableInfo" ref="baseInfoRef" />
      </TabPane>
      <TabPane tab="字段信息" key="2">
        <XColumnTable :dataSource="tableInfo.items" ref="tableRef" />
      </TabPane>
    </Tabs>
    <template #rightFooter>
      <a-button type="primary" danger @click="handleClose" style="margin-right: 10px"> 关闭</a-button>
      <a-button type="primary" @click="handleSubmit"> 提交</a-button>
    </template>
  </PageWrapper>
</template>
<script lang="ts">
  import { BasicForm } from '/@/components/Form';
  import { computed, defineComponent, onMounted, ref, unref } from 'vue';
  import { Card, Tabs } from 'ant-design-vue';
  import { PageWrapper } from '/@/components/Page';
  import XColumnTable from './XColumnTable.vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import * as _API from '../api';
  import { useRouter } from 'vue-router';
  import BaseInfo from './BaseInfo.vue';
  import { useTabs } from '/@/hooks/web/useTabs';

  export default defineComponent({
    name: 'EditTable',
    components: {
      BasicForm,
      BasicTable,
      XColumnTable,
      TableAction,
      PageWrapper,
      Tabs,
      TabPane: Tabs.TabPane,
      [Card.name]: Card,
      BaseInfo,
    },
    setup() {
      const tableRef = ref<{ getData: () => any } | null>(null);
      const baseInfoRef = ref<{ baseValidate: () => any; genValidate: () => any; paramsValidate: () => any; getParamsValue: () => any } | null>(null);
      const tableInfo = ref({});
      let { closeCurrent } = useTabs();

      const { currentRoute } = useRouter();
      const params = computed(() => {
        return unref(currentRoute).params;
      });
      onMounted(async () => {
        tableInfo.value = await _API.getDetailAPI(params.value.tableId.toString());
      });

      function handleClose() {
        closeCurrent();
      }

      async function handleSubmit() {
        try {
          let tableResult = {
            tableId: params.value.tableId.toString(),
            columns: [],
          };
          if (baseInfoRef.value) {
            const [values, taskValues] = await Promise.all([baseInfoRef.value.baseValidate(), baseInfoRef.value.genValidate()]);
            tableResult = { ...tableResult, ...values, ...taskValues, ...baseInfoRef.value.getParamsValue() };
          }
          if (tableRef.value) {
            tableResult.columns = tableRef.value.getData();
          }
          _API.editAPI(tableResult).then(() => closeCurrent());
        } catch (error) {
          console.log(error);
        }
      }

      return {
        activeKey: ref('2'),
        tableInfo,
        tableRef,
        handleSubmit,
        baseInfoRef,
        handleClose,
      };
    },
  });
</script>
<style lang="less" scoped></style>
